package com.nervenets.web.controller.handler.admin.movie;

import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.MovieStatus;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.film.Movie;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class MovieStatusChangeHandler extends SessionHandler<MovieStatusChangeParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(MovieStatusChangeParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getMovieId(), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                final Movie movie = userDao.findById(params.getMovieId(), Movie.class);
                if (null == movie) return errorMessage(MessageCode.code_404, "影片不存在");
                final MovieStatus beforeStatus = movie.getStatus();
                if (!beforeStatus.equals(params.getMovieStatus())) {
                    movie.getInfo().addStatusChange(params.getUserId(), beforeStatus, params.getMovieStatus());
                    movie.setStatus(params.getMovieStatus());
                }
                userDao.saveOrUpdate(movie);

                return successMessage(movie);
            }
        });
    }

    @Override
    public String result() throws Exception {
        return null;
    }
}
